﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;

namespace MathematicallySafe.HeadCounter.Common
{
    static class Utilities
    {
        public static void HyperlinkRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

        public static FrameworkElement FindAncestor(Type ancestorType, Visual visual)
        {
            while (visual != null && !ancestorType.IsInstanceOfType(visual))
            {
                visual = (Visual)VisualTreeHelper.GetParent(visual);
            }
            return visual as FrameworkElement;
        }

        public static FrameworkElement GetItemContainer(ItemsControl itemsControl, Visual bottomMostVisual)
        {
            FrameworkElement itemContainer = null;

            if (itemsControl != null && bottomMostVisual != null && itemsControl.Items.Count >= 1)
            {
                var firstContainer = itemsControl.ItemContainerGenerator.ContainerFromIndex(0);

                if (firstContainer != null)
                {
                    var containerType = firstContainer.GetType();

                    itemContainer = FindAncestor(containerType, bottomMostVisual);

                    if (itemContainer != null && itemContainer.DataContext != null)
                    {
                        var itemContainerVerify = itemsControl.ItemContainerGenerator.ContainerFromItem(itemContainer.DataContext) as FrameworkElement;

                        if (itemContainer != itemContainerVerify)
                        {
                            itemContainer = null;
                        }
                    }
                }
            }

            return itemContainer;
        }
    }
}
